import React, { useState, useEffect, useRef } from 'react';

const InfiniteScroll = ({ loadMore, hasMore, loader, children }) => {
    const [isLoading, setIsLoading] = useState(false);
    const scrollAreaRef = useRef(null);

    const handleScroll = () => {
        if (!isLoading && hasMore &&
            scrollAreaRef.current.scrollHeight - scrollAreaRef.current.scrollTop <= scrollAreaRef.current.clientHeight) {
            setIsLoading(true);
            loadMore().then(() => {
                setIsLoading(false);
            });
        }
    };

    useEffect(() => {
        const scrollArea = scrollAreaRef.current;
        scrollArea.addEventListener('scroll', handleScroll);
        return () => {
            scrollArea.removeEventListener('scroll', handleScroll);
        };
    }, [isLoading, hasMore]);

    return (
        <div ref={scrollAreaRef} style={{ height: '100%', overflowY: 'auto' }}>
            {children}
            {isLoading && loader}
        </div>
    );
};

export default InfiniteScroll;